<template>
  <div class="user-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="left">
            <span class="title">用户管理</span>
            <el-input
              v-model="searchKeyword"
              placeholder="请输入关键词搜索"
              style="width: 200px; margin-left: 20px"
              clearable
              @input="debouncedSearch"
              @clear="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <el-button type="primary" @click="handleAdd">添加用户</el-button>
        </div>
      </template>

      <el-table :data="filteredTableData" style="width: 100%">
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column prop="role" label="角色" width="180" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!formData.id">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
            v-model="formData.role"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

// 初始化数据
const initTableData = [
  {
    id: 1,
    username: 'admin',
    role: '管理员',
    email: 'admin@example.com',
    createTime: '2024-01-01 12:00:00',
  },
  {
    id: 2,
    username: 'user',
    role: '普通用户',
    email: 'user@example.com',
    createTime: '2024-01-02 12:00:00',
  },
];

const tableData = ref([]);
const searchKeyword = ref('');
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref(null);

// 角色选项
const roleOptions = [
  { value: '管理员', label: '管理员' },
  { value: '普通用户', label: '普通用户' },
];

const formData = reactive({
  id: '',
  username: '',
  password: '',
  email: '',
  role: '',
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
};

// 重置表单 - 移到前面
const resetForm = () => {
  formRef.value?.resetFields();
  Object.assign(formData, {
    id: '',
    username: '',
    password: '',
    email: '',
    role: '',
  });
};

// 保存数据到 localStorage
const saveData = () => {
  localStorage.setItem('userData', JSON.stringify(tableData.value));
};

// 搜索处理函数（如果需要特殊处理可以在这里添加）
const handleSearch = () => {
  // 由于使用了计算属性，这里可以为空
  // 如果需要特殊处理（如防抖）可以在这里添加
};

// 可选：添加防抖处理
const debounce = (fn, delay) => {
  let timer = null;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 使用防抖的搜索处理
const debouncedSearch = debounce(() => {
  handleSearch();
}, 300);

// 初始化数据
onMounted(() => {
  const savedData = localStorage.getItem('userData');
  if (savedData) {
    tableData.value = JSON.parse(savedData);
  } else {
    tableData.value = initTableData;
    localStorage.setItem('userData', JSON.stringify(initTableData));
  }
});

// 添加用户
const handleAdd = () => {
  dialogTitle.value = '添加用户';
  dialogVisible.value = true;
};

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户';
  Object.assign(formData, row);
  dialogVisible.value = true;
};

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const index = tableData.value.findIndex((item) => item.id === row.id);
      if (index > -1) {
        tableData.value.splice(index, 1);
        saveData();
        ElMessage.success('删除成功');
      }
    })
    .catch(() => {});
};

// 提交表单
const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (formData.id) {
        // 编辑
        const index = tableData.value.findIndex(
          (item) => item.id === formData.id,
        );
        if (index > -1) {
          tableData.value[index] = { ...formData };
          ElMessage.success('编辑成功');
        }
      } else {
        // 添加
        const newUser = {
          ...formData,
          id: tableData.value.length + 1,
          createTime: new Date().toLocaleString(),
        };
        tableData.value.push(newUser);
        ElMessage.success('添加成功');
      }
      saveData();
      dialogVisible.value = false;
      resetForm();
    }
  });
};

// 通过计算属性实现搜索过滤
const filteredTableData = computed(() => {
  const keyword = searchKeyword.value.toLowerCase().trim();
  if (!keyword) return tableData.value;

  return tableData.value.filter((item) => {
    return (
      item.username.toLowerCase().includes(keyword) ||
      item.email.toLowerCase().includes(keyword) ||
      item.role.toLowerCase().includes(keyword) ||
      item.createTime.toLowerCase().includes(keyword)
    );
  });
});
</script>

<style scoped>
.user-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}
</style>
